<?php

namespace wap\models;

use ijony\helpers\Image;
use ijony\helpers\Url;
use ijony\helpers\Utils;
use Yii;

/**
 * This is the model class for table "{{%products}}".
 *
 * @property string $id 产品 ID
 * @property string $category_id 分类 ID
 * @property string $name 名称
 * @property string $preview 主图
 * @property int $created_at 创建时间
 * @property int $updated_at 修改时间
 * @property int $status 状态
 *
 * @property \wap\models\Attributes[] $attrs
 * @property \wap\models\Cases[] $cases
 * @property \wap\models\Categories $category
 */
class Products extends \common\models\Products
{

    public function afterFind()
    {
        parent::afterFind();

        if($this->veneer){
            $this->veneer = explode(",", $this->veneer);
        }

        if($this->outside_handle){
            $this->outside_handle = explode(",", $this->outside_handle);
        }

        if($this->inside_handle){
            $this->inside_handle = explode(",", $this->inside_handle);
        }

        if($this->lockset){
            $this->lockset = explode(",", $this->lockset);
        }
    }

    public function getCategory()
    {
        return $this->hasOne(Categories::className(), ['id' => 'category_id']);
    }

    public function getCases()
    {
        return $this->hasMany(Cases::className(), ['id' => 'case_id'])->alias('case')->viaTable(CaseProducts::tableName(), ['product_id' => 'id']);
    }

    public function getViewUrl()
    {
        return Url::to(['product/view', 'id' => $this->id]);
    }

    public function getPreviewUrl($width = 0, $height = 0, $cut = true)
    {
        return Image::getImg($this->preview, $width, $height, true, $cut ? Image::THUMB_MODE_CUT : Image::THUMB_MODE_FILL);
    }

    public function getAttrGroup()
    {
        return [
            'veneer' => '内饰面',
            'outside_handle' => '外把手',
            'inside_handle' => '内把手',
            'lockset' => '锁具',
        ];
    }

    public function showAttrName($id, $pos)
    {
        if(!$id){
            return;
        }

        $params = Yii::$app->params[$pos];

        if($pos == 'veneer'){
            $params = array_merge(Yii::$app->params[$pos]['铜饰面'], Yii::$app->params[$pos]['木饰面']);
        }

        return $params[$id];
    }
}
